package com.yz.book.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yz.book.entity.User;
import com.yz.book.service.OrderService;
import com.yz.book.service.UserService;
import com.yz.book.utils.CookieUtils;
import com.yz.book.utils.JwtUtils;
import com.yz.book.vo.CartOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ste
 * @since 2023-02-04 03:37:37
 */
@Controller
@RequestMapping("/order")
public class OrderController {


    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;

    private User getCurrentUser(HttpServletRequest request) {
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String currentUserAccount = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        User currentUser = userService.getUserByUsername(currentUserAccount);

        return currentUser;
    }


    @RequestMapping("allItems")
    @ResponseBody
    public CartOrder allItems(@RequestParam("productIds[]") Integer[] productIds, HttpServletRequest request) {

        //获取用户信息
        User currentUser = getCurrentUser(request);

        //从购物车里获取详情
        CartOrder cartOrder = orderService.getCartOrder(currentUser.getId(), productIds);

        return cartOrder;
    }


    @RequestMapping("createOrder")
    @ResponseBody
    public String createOrder(@RequestParam("productIds[]") Integer[] productIds, Integer addressId, HttpServletRequest request) {

        //获取当前用户信息
        User currentUser = getCurrentUser(request);

        try {
            orderService.createOrder(currentUser, productIds, addressId);
        } catch (RuntimeException e) {
            return e.getMessage();
        }

        return "ok";
    }


    @RequestMapping("all")
    @ResponseBody
    public Page all(HttpServletRequest request,
                    @RequestParam(defaultValue = "1") Integer currentPage,
                    @RequestParam(defaultValue = "2") Integer pageSize
    ) {

        //获取用户信息
        User currentUser = getCurrentUser(request);

        //获取用户的所有订单
        Page page = orderService.queryAllOrder(currentUser.getId(), currentPage, pageSize);

        return page;
    }


    @RequestMapping("updateStatus")
    @ResponseBody
    public void updateStatus(Integer orderId, Integer newStatus) {

        orderService.updateState(orderId, newStatus);

    }


}

